package com.fangwaii.core.socket.handlers;

import com.fangwaii.core.mapping.HttpStatement;
import com.fangwaii.core.session.Configuration;
import com.fangwaii.core.socket.BaseHandler;
import com.fangwaii.core.socket.agreement.AgreementConstants;
import com.fangwaii.core.socket.agreement.GatewayResult;
import com.fangwaii.core.socket.agreement.ResponseParser;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lxc18
 * @date 2024/12/6 19:34
 * @description AuthorizationHandler
 */
public class AuthorizationHandler extends BaseHandler<FullHttpRequest> {
    private Configuration configuration;

    public AuthorizationHandler(Configuration configuration) {
        this.configuration = configuration;
    }

    private final Logger logger = LoggerFactory.getLogger(GatewayServerHandler.class);
    @Override
    protected void session(ChannelHandlerContext channelHandlerContext, Channel channel, FullHttpRequest request) {
        // 1. 解析参数
        try {
            HttpStatement httpStatement = channel.attr(AgreementConstants.HTTP_STATEMENT).get();
            if(httpStatement.isAuth()){
                //拿到id,token
                HttpHeaders header = request.headers();//获取Netty内置的请求头对象
                String uId = header.get("uId");
                String token = header.get("token");
                //参数校验
                if (null == token || "".equals(token)) {
                    DefaultFullHttpResponse response = new ResponseParser().parse(GatewayResult.gatewayFail(AgreementConstants.ResponseCode._400.getCode(), "对不起，你的 token 不合法！"));
                    channel.writeAndFlush(response);
                }
                //将多次使用的实例放到全局配置类对象中
                boolean validAuth = configuration.validAuth(uId, token);

                //shiro+jwt如果验证通过就放心
                if(validAuth){
                    //放行
                    request.retain();
                    channelHandlerContext.fireChannelRead(request);
                }
                else{
                    //如果不通过就返回
                    DefaultFullHttpResponse response = new ResponseParser().parse(GatewayResult.gatewayFail(AgreementConstants.ResponseCode._403.getCode(), "对不起，你无权访问此接口！"));
                    channel.writeAndFlush(response);
                }

            }
            else{
                //放行
                request.retain();
                channelHandlerContext.fireChannelRead(request);
            }
        } catch (Exception e) {
            //直接返回无权限
            DefaultFullHttpResponse response = new ResponseParser().parse(GatewayResult.gatewayFail(AgreementConstants.ResponseCode._500.getCode(), "网关协议调用失败！"));
            channel.writeAndFlush(response);
        }

    }
}
